package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.StampedLock;

@Service
@Slf4j
public class StampedLockCacheService {

    private final StampedLock stampedLock = new StampedLock();
    private final Map<String, String> cache = new ConcurrentHashMap<>(); // 使用ConcurrentHashMap作为缓存

    // 缓存读取示例
    public String readFromCache(String key) {
        long stamp = stampedLock.tryOptimisticRead();  // 尝试乐观读
        String value = cache.get(key);  // 读取共享资源作为缓存值
        if (!stampedLock.validate(stamp)) {  // 验证乐观读期间是否有写操作
            stamp = stampedLock.readLock();  // 获取悲观读锁
            try {
                value = cache.get(key);  // 再次读取共享资源
            } finally {
                stampedLock.unlockRead(stamp);  // 释放读锁
            }
        }
        log.info("缓存读取到的值为: {}", value);
        return value;
    }

    // 缓存写入示例
    public void writeToCache(String key, String value) {
        long stamp = stampedLock.writeLock();  // 获取写锁
        try {
            cache.put(key, value);  // 写入共享资源
            log.info("写入缓存: {} -> {}", key, value);
        } finally {
            stampedLock.unlockWrite(stamp);  // 释放写锁
        }
    }
}
